package ext.workflow;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.ptc.netmarkets.util.beans.NmCommandBean;
import com.ptc.netmarkets.work.NmWorkItemCommands;

import wt.access.AccessPermission;
import wt.doc.WTDocument;
import wt.log4j.LogR;
import wt.method.RemoteAccess;
import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTUser;
import wt.project.Role;
import wt.session.SessionHelper;
import wt.team.Team;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.wip.WorkInProgressHelper;
import wt.workflow.engine.WfActivity;
import wt.workflow.engine.WfProcess;
import wt.workflow.work.WorkItem;

public class WfActivityCompleteEvent extends NmWorkItemCommands implements RemoteAccess, Serializable {
	/** Log4j Logger. */
	private static final Logger LOGGER = LogR.getLogger(WfActivityCompleteEvent.class.getName());

	// 判断签审角色是否为空，成员是否有签审权限
	public static void doSetParticipator(NmCommandBean cb, String str) throws Exception {
		WTUser currentuser = (WTUser) SessionHelper.manager.getPrincipal();
		WTUser admin = (WTUser) SessionHelper.manager.setAdministrator();

		String oid = cb.getActionOid().toString();// 得到oid
		// 通过获取配置文件的方式来代替参与者模板的方式来获取数据源
		HttpServletRequest request = cb.getRequest();
		String roleAndUser = request.getParameter("roleAndUser");
		LOGGER.debug("...........roleAndUser:" + roleAndUser);
		// "zzz;;;jiaoduihhh;;;zzz;;;shenhehhh;;;xiaozhengmaohhh;;;zzz;;;huiqianhhh;;;zzz;;;pizhun";
		// zzz;;;角色hhh;;;参与者(分隔符hhh;;;)
		String[] data = roleAndUser.split("hhh;;;");// 得到参与者和zzz;;;角色
		String getData;
		String role_value = null;
		WTUser user = null;
		WfProcess process = WorkFlowUtil.GetWfProcess(oid);

		Team team = (Team) process.getTeamId().getObject();
		WTPrincipal principal = wt.session.SessionHelper.getPrincipal();
		Vector paramVector = new Vector();
		paramVector.add(AccessPermission.ALL);
		// 赋予用户访问该对象权限
		WorkFlowUtil.setObjectAccessModify(team, principal, paramVector);
		try {
			WorkFlowUtil.deleteAllUser(process);// 清空流程角色中的所有用户
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (int i = 0; i < data.length; i++) {
			getData = data[i].toString();
			if (getData.indexOf("zzz;;;") == -1)// 判断字符串是否存在zzz;;;，有就是角色，没有就是参与者==-1
			{
				// 参与者分为组和用户
				user = WorkFlowUtil.GetUserByName(getData);
				if (user == null) {
					WTGroup group = WorkFlowUtil.getGroup(getData);
					List<WTUser> listUser = WorkFlowUtil.getGroupMembersOfUser(group);
					for (int j = 0; j < listUser.size(); j++) {
						try {
							WorkFlowUtil.addPrincipalToRole(process, role_value, listUser.get(j));
						} catch (WTPropertyVetoException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

				} else {
					LOGGER.debug("..........参与者name:" + user.getName());
					try {
						WorkFlowUtil.addPrincipalToRole(process, role_value, user);
					} catch (WTPropertyVetoException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			} else {
				role_value = getData.substring(6);
				LOGGER.debug("doSetParticipator............角色" + role_value);
			}
		}
		Role getrole;
		String key;
		Map map = doGetRoleAndUser(cb, str, roleAndUser);
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			getrole = (Role) it.next();
			key = getrole.toString();
			LOGGER.debug("key—————————————————value:" + key + "............" + getrole.getDisplay()
					+ getrole.getDisplay(Locale.CHINA));
			/**
			 * bianzhi编制 xiaodui校对 shenhe审核 huiqian会签 pizhun批准
			 */

			ArrayList value = (ArrayList) map.get(getrole);
			LOGGER.debug("角色，用户数量：" + getrole + value.size());
			if (value.size() == 0) {
				throw new WTException(getrole.getDisplay(Locale.CHINA) + "角色没有选择参与者！");
			}
		}
		WTUser userRE = (WTUser) SessionHelper.manager.setPrincipal(currentuser.getAuthenticationName());

	}

	// 获取role-user键值集合
	public static Map<Role, List<WTUser>> doGetRoleAndUser(NmCommandBean cb, String str, String roleandUser)
			throws Exception {
		Map<Role, List<WTUser>> roleAndUserMap = new HashMap<Role, List<WTUser>>();
		List<WTUser> userList = new ArrayList<WTUser>();
		String roleAndUser = roleandUser;
		String[] data = roleAndUser.split("hhh;;;");
		String getData;
		String role_value = null;
		Role role = null;
		WTUser user = null;
		for (int i = 0; i < data.length; i++) {
			getData = data[i].toString();
			if (getData.indexOf("zzz;;;") == -1)// 判断字符串是否存在zzz;;;，有就是角色，没有就是参与者==-1
			{
				LOGGER.debug("doGetRoleAndUser的参与者" + getData);
				// 参与者分为组和用户
				user = WorkFlowUtil.GetUserByName(getData);
				if (user == null) {
					WTGroup group = WorkFlowUtil.getGroup(getData);
					List<WTUser> listUser = WorkFlowUtil.getGroupMembersOfUser(group);
					for (int j = 0; j < listUser.size(); j++) {
						userList.add(listUser.get(j));
					}
				} else {
					userList.add(user);
				}
			} else {
				role_value = getData.substring(6);
				LOGGER.debug("doGetRoleAndUser的角色" + role_value);
				userList = new ArrayList<WTUser>();
				String roleValue[] = str.split(",");
				for (int j = 0; j < roleValue.length; j++) {
					if (roleValue[j].equals(role_value)) {
						role = Role.toRole(role_value);
						roleAndUserMap.put(role, userList);
					}
				}
			}
		}
		return roleAndUserMap;

	}

	/**
	 * 图纸审批（升级流程）
	 * 
	 * @param cb
	 * @throws Exception
	 */
	public static void doEE(NmCommandBean cb) throws Exception {
		LOGGER.debug("................doEE go to start................");
		WorkItem workItem = (WorkItem) cb.getActionOid().getRef();
		// 获取活动
		WfActivity activity = (WfActivity) workItem.getSource().getObject();
		// 获取活动名称
		String activityname = activity.getName();
		// 获取活动id
		String oid = cb.getActionOid().toString();
		// 获取工作流
		WfProcess process = WorkFlowUtil.GetWfProcess(oid);
		// 获取pbo
		Object pbo = workItem.getPrimaryBusinessObject().getObject();
		if ("EE代码提交".equals(activityname.toString())) {
			WTDocument doc = null;
			if (pbo instanceof WTDocument) {
				doc = (WTDocument) pbo;
			}
			if (null == doc) {
				throw new WTException("签审文档不存在!");
			}
			if (WorkInProgressHelper.isCheckedOut(doc)) {
				throw new WTException("签审文档被检出，请检入!");
			}
			String rolestr = WorkFlowUtil.getProcessVariable(process, "addRoleBtn");
			;
			LOGGER.debug(".............addRoleBtn:" + rolestr);
			WfActivityCompleteEvent.doSetParticipator(cb, rolestr);
			// NmWorkItemCommands.complete(cb);
		}
	}
}
